import os as system_os
import sys
import shutil
import subprocess

class MyOS:
    def __init__(self):
        self.commands = {
            'help': self.help,
            'exit': self.exit,
            'ls': self.ls,
            'pwd': self.pwd,
            'cd': self.cd,
            'mkdir': self.mkdir,
            'rmdir': self.rmdir,
            'rm': self.delete,
            'cp': self.copy,
            'mv': self.move,
            'touch': self.touch,
            'cat': self.cat,
            'echo': self.echo,
            'cls': self.cls,
            'node': self.node_run,
            'npm': self.npm_run,
            'install': self.install,
            'pip': self.pip_install,
            'del_install': self.del_install,
            'nmap': self.nmap_scan,
            'aircrack': self.aircrack_run,
            'disconnect': self.disconnect_network,
            'connect': self.connect_network,
        }

    def help(self):
        print("Available commands:")
        for command in self.commands.keys():
            print(f" - {command}")

    def exit(self):
        print("Exiting the simple OS.")
        sys.exit()

    def ls(self):
        print("Listing files and directories:")
        for item in system_os.listdir('.'):
            print(item)

    def pwd(self):
        print("Current directory:", system_os.getcwd())

    def cd(self, path):
        if not path:
            print("Invalid command format.")
            return
        try:
            system_os.chdir(path)
            print(f"Changed directory to {path}")
        except FileNotFoundError:
            print(f"No such file or directory: {path}")
            print("Current directory contents:")
            self.ls()

    def mkdir(self, directory):
        if not directory:
            print("Invalid command format.")
            return
        try:
            result = subprocess.run(['sudo', 'mkdir', directory], capture_output=True, text=True)
            if result.returncode == 0:
                print(f"Directory '{directory}' created.")
            else:
                print("Error:", result.stderr)
        except Exception as e:
            print(f"Failed to create directory: {e}")

    def rmdir(self, directory):
        if not directory:
            print("Invalid command format.")
            return
        try:
            result = subprocess.run(['sudo', 'rmdir', directory], capture_output=True, text=True)
            if result.returncode == 0:
                print(f"Directory '{directory}' removed.")
            else:
                print("Error:", result.stderr)
        except Exception as e:
            print(f"Failed to remove directory: {e}")

    def delete(self, file):
        if not file:
            print("Invalid command format.")
            return
        try:
            result = subprocess.run(['sudo', 'rm', file], capture_output=True, text=True)
            if result.returncode == 0:
                print(f"File '{file}' deleted.")
            else:
                print("Error:", result.stderr)
        except Exception as e:
            print(f"Failed to delete file: {e}")

    def copy(self, src, dst):
        if not src or not dst:
            print("Invalid command format.")
            return
        try:
            result = subprocess.run(['sudo', 'cp', src, dst], capture_output=True, text=True)
            if result.returncode == 0:
                print(f"Copied '{src}' to '{dst}'.")
            else:
                print("Error:", result.stderr)
        except Exception as e:
            print(f"Failed to copy file: {e}")

    def move(self, src, dst):
        if not src or not dst:
            print("Invalid command format.")
            return
        try:
            result = subprocess.run(['sudo', 'mv', src, dst], capture_output=True, text=True)
            if result.returncode == 0:
                print(f"Moved '{src}' to '{dst}'.")
            else:
                print("Error:", result.stderr)
        except Exception as e:
            print(f"Failed to move file: {e}")

    def touch(self, filename):
        if not filename:
            print("Invalid command format.")
            return
        try:
            result = subprocess.run(['sudo', 'touch', filename], capture_output=True, text=True)
            if result.returncode == 0:
                print(f"File '{filename}' created or updated.")
            else:
                print("Error:", result.stderr)
        except Exception as e:
            print(f"Failed to create or update file: {e}")

    def cat(self, filename):
        if not filename:
            print("Invalid command format.")
            return
        try:
            with open(filename, 'r') as file:
                print(file.read())
        except FileNotFoundError:
            print(f"No such file: {filename}")

    def echo(self, text):
        if not text:
            print("Invalid command format.")
            return
        print(text)

    def cls(self):
        system_os.system('cls' if system_os.name == 'nt' else 'clear')

    def node_run(self, script):
        if not script:
            print("Invalid command format.")
            return
        try:
            result = subprocess.run(['node', script], capture_output=True, text=True)
            print(result.stdout)
            if result.stderr:
                print("Error:", result.stderr)
        except FileNotFoundError:
            print("Node.js is not installed or the script does not exist.")

    def npm_run(self, command):
        if not command:
            print("Invalid command format.")
            return
        try:
            result = subprocess.run(['npm'] + command.split(), capture_output=True, text=True)
            print(result.stdout)
            if result.stderr:
                print("Error:", result.stderr)
        except FileNotFoundError:
            print("npm is not installed, or the command is incorrect.")

    def install(self, package):
        if not package:
            print("Invalid command format.")
            return
        try:
            result = subprocess.run(['sudo', 'apt', 'install', package, '-y'], capture_output=True, text=True)
            print(result.stdout)
            if result.stderr:
                print("Error:", result.stderr)
        except Exception as e:
            print(f"Failed to install package: {e}")

    def pip_install(self, package):
        if not package:
            print("Invalid command format.")
            return
        try:
            result = subprocess.run(['sudo', 'pip', 'install', package], capture_output=True, text=True)
            print(result.stdout)
            if result.stderr:
                print("Error:", result.stderr)
        except Exception as e:
            print(f"Failed to install package: {e}")

    def del_install(self, package):
        if not package:
            print("Invalid command format.")
            return
        try:
            result = subprocess.run(['sudo', 'apt', 'remove', package, '-y'], capture_output=True, text=True)
            print(result.stdout)
            if result.stderr:
                print("Error:", result.stderr)
        except Exception as e:
            print(f"Failed to remove package: {e}")

    def nmap_scan(self, target):
        if not target:
            print("Invalid command format.")
            return
        try:
            result = subprocess.run(['sudo', 'nmap', target], capture_output=True, text=True)
            print(result.stdout)
            if result.stderr:
                print("Error:", result.stderr)
        except Exception as e:
            print(f"Failed to scan: {e}")

    def aircrack_run(self, interface):
        if not interface:
            print("Invalid command format.")
            return
        try:
            result = subprocess.run(['sudo', 'aircrack-ng', interface], capture_output=True, text=True)
            print(result.stdout)
            if result.stderr:
                print("Error:", result.stderr)
        except Exception as e:
            print(f"Failed to run aircrack-ng: {e}")

    def disconnect_network(self, interface):
        if not interface:
            print("Invalid command format.")
            return
        try:
            result = subprocess.run(['sudo', 'ifconfig', interface, 'down'], capture_output=True, text=True)
            if result.returncode == 0:
                print(f"Disconnected network interface: {interface}")
            else:
                print("Error:", result.stderr)
        except Exception as e:
            print(f"Failed to disconnect network: {e}")

    def connect_network(self, interface):
        if not interface:
            print("Invalid command format.")
            return
        try:
            result = subprocess.run(['sudo', 'ifconfig', interface, 'up'], capture_output=True, text=True)
            if result.returncode == 0:
                print(f"Connected network interface: {interface}")
            else:
                print("Error:", result.stderr)
        except Exception as e:
            print(f"Failed to connect network: {e}")

    def run(self):
        while True:
            command = input(">>> ").strip().split()
            if not command:
                continue
            cmd = command[0]
            args = command[1:]

            if cmd in self.commands:
                self.commands[cmd](' '.join(args))
            else:
                print("Invalid command format.")

if __name__ == "__main__":
    my_os = MyOS()
    my_os.run()